package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.githang.statusbar.StatusBarCompat;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.ramos.kuaixiao.MyView.refresh.SwipyRefreshLayout;
import com.ramos.kuaixiao.MyView.refresh.SwipyRefreshLayoutDirection;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.adapter.ProductResultAdapter;
import com.ramos.kuaixiao.db.BrandInfoDB;
import com.ramos.kuaixiao.db.PriceDB;
import com.ramos.kuaixiao.db.StoreNumDB;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.entity.ShopTypeBean;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;

import org.apache.http.Header;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProductResultActivity extends BaseActivity implements OnClickListener, SwipyRefreshLayout.OnRefreshListener {
    private static String TAG = "ProductResultActivity";
    private Context mContext;
    public final static int SCANNIN_GREQUEST_CODE = 0xb1;

    //结果列表分页
    String custmerId;
    String mCurrentBrand;
    public static List<ShopTypeBean.ShopType.ProductInfo> mProducts = new ArrayList<>();
    List<ShopTypeBean.ShopType.ProductInfo> data;
    public List<ShopTypeBean.ShopType.ProductInfo> mPageProducts = new ArrayList<>();
    private int page = 1;
    private RecyclerView recListView;
    private SwipyRefreshLayout mRefreshLayout;
    private LinearLayoutManager mLinearLayoutManager;
    private ProductResultAdapter mResutAdapter;

    private ImageView saoyisao;
    private LinearLayout rl_choose;
    TextView tv_search_result;

    BrandInfoDB mBrand;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;
    public final static int GET_PRICE_SUCCESS = 400;
    SearchView searchview;
    Customer mCustomer;
    String mScanCode;
    private RelativeLayout re_home_shop;
    private RelativeLayout re_home_order;
    private RelativeLayout re_home_task;
    private RelativeLayout re_home_my;
    private TextView tv_home_shop;
    private TextView tv_home_order;
    private TextView tv_home_task;
    private TextView tv_home_my;
    private ImageView ib_home_shop;
    private ImageView ib_home_order;
    private ImageView ib_home_task;
    private ImageView ib_home_my;
    private CheckBox cb_select_goods;
    int position = -1;
    int groupPosition = -1;
    public void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(R.layout.activity_product_result);
        initView();
        initTabView();
    }

    private void initView() {
        position = -1;
        mContext = this;
        mBrand = new BrandInfoDB();
        mCustomer = (Customer) getIntent().getExtras().get("customer");
        mProducts.clear();
        if (getIntent().getSerializableExtra("result") != null) {
            mProducts.addAll((List<ShopTypeBean.ShopType.ProductInfo>) getIntent().getSerializableExtra("result"));//获取list方式
        }
        Log.d(TAG, "mProducts:" + mProducts.size());
        mScanCode = (String) getIntent().getExtras().get("scan_code");
        mCurrentBrand = (String) getIntent().getExtras().get("brand");
        if(getIntent().getExtras().get("position") != null){
            position = (Integer) getIntent().getExtras().get("position");
        }
        if(getIntent().getExtras().get("groupPosition") != null){
            groupPosition = (Integer) getIntent().getExtras().get("groupPosition");
        }

        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title), false);
        rl_choose = (LinearLayout) findViewById(R.id.rl_choose);
        rl_choose.setOnClickListener(this);
        saoyisao = (ImageView) findViewById(R.id.saoyisao);
        saoyisao.setBackgroundColor(Color.TRANSPARENT);
        saoyisao.setOnClickListener(this);
        tv_search_result = (TextView) findViewById(R.id.tv_search_result);
        cb_select_goods = (CheckBox) findViewById(R.id.cb_select_goods);
        //SharedPreference.setPreferBoolean("isAllShop", false);
        if(SharedPreference.hasPreferString("isAllShop") && SharedPreference.getPreferBoolean("isAllShop")){
            cb_select_goods.setChecked(true);
        } else {
            cb_select_goods.setChecked(false);
        }

        cb_select_goods.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    SharedPreference.setPreferBoolean("isAllShop", false);
                } else {
                    SharedPreference.setPreferBoolean("isAllShop", true);
                }
            }
        });
        searchview = (SearchView) findViewById(R.id.searchview);
        int id = searchview.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        TextView textView = (TextView) searchview.findViewById(id);
        textView.setTextSize(16);//字体、提示字体大小
        searchview.setQueryHint("搜索商品(至少输入两个字)");
        searchview.setIconified(false);
        searchview.setIconifiedByDefault(false);
        int magId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
        ImageView magImage = (ImageView) searchview.findViewById(magId);
        magImage.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
        Class<?> c = searchview.getClass();
        try {
            Field f = c.getDeclaredField("mSearchPlate");//通过反射，获得类对象的一个属性对象
            f.setAccessible(true);//设置此私有属性是可访问的
            View v = (View) f.get(searchview);//获得属性的值
            v.setBackgroundColor(Color.TRANSPARENT);//设置此view的背景
        } catch (Exception e) {
            e.printStackTrace();
        }
        searchview.clearFocus();

        mRefreshLayout = (SwipyRefreshLayout) findViewById(R.id.swipyrefreshlayout);
        mRefreshLayout.setDirection(SwipyRefreshLayoutDirection.BOTTOM);
        mRefreshLayout.setOnRefreshListener(this);
        recListView = (RecyclerView) findViewById(R.id.productListView);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recListView.setLayoutManager(mLinearLayoutManager);

        searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String arg0) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean onQueryTextChange(String queryText) {
                if (StringUtil.isEmpty(queryText) || queryText.length() < 2) {
                    //showList();
                    data = new ArrayList<>();
                    mResutAdapter.refresh(data);
                    //mResutAdapter.getFilter().filter(null);
                    tv_search_result.setText("0" + mContext.getResources().getString(R.string.shop_result));
                } else if (queryText.length() < 4 && queryText.length() >= 2) {
                    Pattern p = Pattern.compile("[0-9]*");
                    Matcher m = p.matcher(queryText);
                    if (!m.matches()) {
                        showSearch();
                        mResutAdapter.getFilter().filter(queryText);
                    }
                } else if (queryText.length() >= 3) {
                    showSearch();
                    mResutAdapter.getFilter().filter(queryText);
                }
                return true;
            }
        });
        mPageProducts = getPageList(mProducts);
        Log.d(TAG, "mPageProducts:" + mPageProducts.size());
        mResutAdapter = new ProductResultAdapter(this, mPageProducts, mCustomer);
        recListView.setAdapter(mResutAdapter);
        tv_search_result.setText(mProducts.size() + mContext.getResources().getString(R.string.shop_result)+"(价格为0不显示)");
        mResutAdapter.setUpdateCarListener(new UpdateListener());
        getWare(mPageProducts);
        if (!StringUtil.isEmpty(mScanCode)) {
            searchview.setQuery(mScanCode, true);
        }
        /*if(groupPosition == 0 && position == 0 && !StringUtil.isEmpty(mCurrentBrand)){
            searchview.setQuery(mCurrentBrand, true);
        }*/
        /*if(mProducts.size() == 0 && !StringUtil.isEmpty(mCurrentBrand)){
            searchview.setQuery(mCurrentBrand, true);
        }*/

    }

    private void initTabView() {
        re_home_shop = (RelativeLayout) findViewById(R.id.re_home_shop);
        re_home_order = (RelativeLayout) findViewById(R.id.re_home_order);
        re_home_task = (RelativeLayout) findViewById(R.id.re_home_task);
        re_home_my = (RelativeLayout) findViewById(R.id.re_home_my);
        re_home_shop.setOnClickListener(this);
        re_home_order.setOnClickListener(this);
        re_home_task.setOnClickListener(this);
        re_home_my.setOnClickListener(this);

        ib_home_shop = ((ImageView) findViewById(R.id.ib_home_shop));
        ib_home_order = ((ImageView) findViewById(R.id.ib_home_order));
        ib_home_task = ((ImageView) findViewById(R.id.ib_home_task));
        ib_home_my = ((ImageView) findViewById(R.id.ib_home_my));

        tv_home_shop = ((TextView) findViewById(R.id.tv_home_shop));
        tv_home_order = ((TextView) findViewById(R.id.tv_home_order));
        tv_home_task = ((TextView) findViewById(R.id.tv_home_task));
        tv_home_my = ((TextView) findViewById(R.id.tv_home_my));

        ib_home_shop.setImageResource(R.drawable.tab_infomation_clk);
        tv_home_shop.setTextColor(getResources().getColor(R.color.title));

        ib_home_order.setImageResource(R.drawable.tab_schedule);
        tv_home_order.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_task.setImageResource(R.drawable.tab_service);
        tv_home_task.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_my.setImageResource(R.drawable.tab_contacts);
        tv_home_my.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

    }

    @Override
    protected void onResume() {
        super.onResume();
        searchview.clearFocus();
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private void showSearch() {
        tv_search_result.setText("0" + this.getResources().getString(R.string.shop_result));
        recListView.setVisibility(View.VISIBLE);
    }

    public void getWare(List<ShopTypeBean.ShopType.ProductInfo> type) {
        WareHouse product = new WareHouse(type);
        product.executeOnExecutor(Executors.newCachedThreadPool());
    }

    @Override
    public void onRefresh(SwipyRefreshLayoutDirection direction) {
        if (direction == SwipyRefreshLayoutDirection.BOTTOM) {
            if (page < (mProducts.size() - 1) / 40 + 1) {
                ++page;
                List<ShopTypeBean.ShopType.ProductInfo> products = getPageList(mProducts);
                if (products.size() > 0) {
                    mPageProducts.addAll(products);
                    Log.d(TAG, "result " + mPageProducts.size());
                    mResutAdapter.notifyDataSetChanged();
                    getWare(products);
                }
            }
            mRefreshLayout.setRefreshing(false);
        }
    }

    private List<ShopTypeBean.ShopType.ProductInfo> getPageList(List<ShopTypeBean.ShopType.ProductInfo> mProducts) {
        List<ShopTypeBean.ShopType.ProductInfo> products = new ArrayList<>();
        if (mProducts.size() <= 40) {
            if (page == 1) {
                products.addAll(mProducts);
            }
        } else {
            int maxPage = (mProducts.size() - 1) / 40 + 1;
            if (page < maxPage) {
                products.addAll(mProducts.subList((page - 1) * 40, page * 40));
            } else if (page == maxPage) {
                products.addAll(mProducts.subList((page - 1) * 40, mProducts.size()));
                ToastUtils.show("数据已加载完");
            }
        }
        return products;
    }

    class WareHouse extends AsyncTask<String, String, String> {
        private List<ShopTypeBean.ShopType.ProductInfo> productList = new ArrayList<>();

        WareHouse(List<ShopTypeBean.ShopType.ProductInfo> type) {
            productList = type;
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                for (int i = 0; i < productList.size(); i++) {
                    final ShopTypeBean.ShopType.ProductInfo product = productList.get(i);
                    getLocalWareAndPrice(product);
                }
                //mResutAdapter.notifyDataSetChanged();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    }

    private void getLocalWareAndPrice(ShopTypeBean.ShopType.ProductInfo product) {
        //只采用本地数据查询价格
        if (StringUtil.isEmpty(mCustomer.getHouseId())) {
            String price  = new PriceDB().getPrice(product.getProductInfoId(), mCustomer.getId());
            String [] types = price.split("_");
            if(types.length>1){
                if(types[1].equals("1")){
                    product.setType(1);
                } else {
                    product.setType(2);
                }
            }else {
                product.setType(2);
            }
            Log.d(TAG, "price:"+price+" types[0]:"+types[0] + " types[1]"+types[1]);
            product.setNonTaxSalePrice(types[0]);
        } else {
            String price  = new PriceDB().getPrice(product.getProductInfoId(), mCustomer.getHouseId());
            String [] types = price.split("_");
            if(types.length>1){
                if(types[1].equals("1")){
                    product.setType(1);
                } else {
                    product.setType(2);
                }
            }else {
                product.setType(2);
            }
            product.setNonTaxSalePrice(types[0]);
        }
        if (StringUtil.isEmpty(mCustomer.getHouseId()) || StringUtil.isEmpty(mCustomer.getHouseName())) {
            product.setTotal(new StoreNumDB().getMaxStoreNum(product.getProductInfoId(), mCustomer.getId() + "", mCustomer.getName() + ""));
        } else {
            product.setTotal(new StoreNumDB().getMaxStoreNum(product.getProductInfoId(), mCustomer.getHouseId() + "", mCustomer.getHouseName() + ""));
        }

        sendMessagea(GET_PRICE_SUCCESS, "");
    }

    public void getWareAndPrice(final ShopTypeBean.ShopType.ProductInfo product) {
        try {
            String url = NetUtils.SHOP_INFO;
            if (mCustomer != null && !StringUtil.isEmpty(mCustomer.getId())) {
                custmerId = mCustomer.getId();
            } else {
                custmerId = SharedPreference.getPreferString("id");
            }
            String path = url + "dealerId=test2&productBarCode=" + product.getProductBarCode() + "&productInfoId=" + product.getProductInfoId() + "&custmerId=" + custmerId
                    + "&userId=" + SharedPreference.getPreferString("id");
            Log.d("getWareAndPrice", "path=" + path);
            SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        Log.d(TAG, "result " + result);
                        org.json.JSONObject user = new org.json.JSONObject(result);
                        if (user.getInt("status") == 200) {
                            JSONObject jsonObejct = JSONObject.parseObject(result);
                            JSONObject data = jsonObejct.getJSONObject("data");
                            com.ramos.kuaixiao.entity.Product product1 = JSONObject.parseObject(data.toString(), com.ramos.kuaixiao.entity.Product.class);
                            String singlePrice = product1.getSalePrice();
                            product.setNonTaxSalePrice(singlePrice);
                            Log.d(TAG, "result :singlePrice " + singlePrice);
                            List<com.ramos.kuaixiao.entity.Product.WareInfo> ware = product1.getWareList();
                            Set<Integer> set = new HashSet<>();
                            if (ware != null && ware.size() > 0) {
                                for (com.ramos.kuaixiao.entity.Product.WareInfo w : ware) {
                                    set.add(w.getCount());
                                }
                                Log.d(TAG, "result :setTotal " + Collections.max(set));
                                //product.setTotal(Collections.max(set));
                            }
                            //notifyDataSetChanged();
                            sendMessagea(GET_PRICE_SUCCESS, result);
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class UpdateListener implements ProductResultAdapter.UpdateCarListener {
        @Override
        public void update(int num, List<ShopTypeBean.ShopType.ProductInfo> tasklist) {
            if (tasklist == null) {
                tv_search_result.setText(0 + mContext.getResources().getString(R.string.shop_result));
                data = new ArrayList<>();
                mResutAdapter.refresh(data);
            } else {
                tv_search_result.setText(num + mContext.getResources().getString(R.string.shop_result));
                mProducts.clear();
                mProducts.addAll(tasklist);
                mPageProducts.clear();
                mPageProducts = getPageList(mProducts);
                mResutAdapter.refresh(mPageProducts);
                getWare(mPageProducts);
            }
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    Log.d(TAG, "result " + msg.obj.toString());
                    break;
                case UPLOAD_FAIL:
                    Log.d(TAG, "result fail");
                    ToastUtils.show("获取数据失败！");
                    break;

                case GET_PRICE_SUCCESS:
                    mResutAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    };

    public void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.saoyisao:
                Intent intent = new Intent();
                intent.setClass(mContext, CaptureActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
                break;
            case R.id.rl_choose:
                finish();

                break;
            /*case R.id.ib_sift_goods:
                if (StringUtil.isEmpty(mCurrentBrand)) {
                    //showList();
                    ToastUtils.show("未获取品牌信息");
                } else {
                    searchview.setQuery(mCurrentBrand, true);
                }
                break;*/
            case R.id.re_home_shop:
                showMain(1);
                break;
            case R.id.re_home_order:
                showMain(2);
                break;
            case R.id.re_home_task:
                showMain(3);
                break;
            case R.id.re_home_my:
                showMain(4);
                break;
            default:
                break;
        }
    }

    public void showMain(int i) {
        Intent intent = new Intent();
        intent.setClass(ProductResultActivity.this, MainActivity.class);
        //一定要指定是第几个pager，因为要跳到ThreeFragment，这里填写2
        intent.putExtra("id", i);
        startActivity(intent);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (resultCode == SCANNIN_GREQUEST_CODE) {
                Log.d(TAG, "onActivityResult " + data.getExtras().getString("scan_code"));
                searchview.setQuery(data.getExtras().getString("scan_code"), true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
